import React, { Component, Suspense, Fragment } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Input,
  Tree,
  Button,
  message,
  Tag,
  Drawer,
} from 'antd';
import { routerRedux } from 'dva/router';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import styles from './index.less';
const FormItem = Form.Item;
const { TreeNode } = Tree;

@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['amendantRecord/fetch'],
}))
class EditShoreNew extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeList: [],
      value: '',
      name: '',
      checkedKeys: [],
      open: [],
      checkButton: true,
      haveCheckedKeys: [],
      close: true,
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetch = () => {
    console.log(this.props.location.params);
    let a = this.props.location.params.id;
    this.setState({ value: a.name });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeBaseSharingNew/fetchc',
        payload: { shareId: a._id },
        callback: res => {
          console.log('列表数据', res);
          this.bus(res);
          let temp = res;
          temp.map((item, index) => (item['key'] = index));
          this.setState({ treeList: temp });
        },
      });
    });
  };

  // fetch = () => {
  //   console.log(this.props.location.params);
  //   var url = location.search;
  //   var theRequest = new Object();
  //   if (url.indexOf('?') != -1) {
  //     var str = url.substr(1);
  //     var strs = str.split('&');
  //     for (var i = 0; i < strs.length; i++) {
  //       theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
  //     }
  //     console.log(theRequest);
  //   }
  //   this.setState({ value: theRequest.name });
  //   const { dispatch, currentUser } = this.props;
  //   this.reqRef = requestAnimationFrame(() => {
  //     dispatch({
  //       type: 'knowledgeBaseSharing/fetchc',
  //       // payload: { shareId: a._id },
  //       payload: { shareId: theRequest._id },
  //       callback: res => {
  //         console.log('列表数据', res);
  //         this.bus(res);
  //         let temp = res;
  //         temp.map((item, index) => (item['key'] = index));
  //         this.setState({ treeList: temp });
  //       },
  //     });
  //   });
  // };

  componentWillMount() {
    this.fetch();
  }

  bus = data => {
    const { checkedKeys } = this.state;
    data.map(item => {
      if (item.children) {
        this.bus(item.children);
      }
      if (item.data.selected) {
        console.log(checkedKeys);
        checkedKeys.push(item.id);
        this.setState({
          checkedKeys: checkedKeys,
          haveCheckedKeys: checkedKeys,
        });
      }
    });
  };

  onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys);
    this.setState({ checkedKeys: checkedKeys });
  };

  onChange = e => {
    console.log(e.target.value);
    this.setState({ value: e.target.value });
  };

  check = () => {
    console.log('我是全选按钮');
    this.setState({ open: [], checkButton: !this.state.checkButton }, () => {
      this.openedTreeNodes(this.state.treeList);
    });
  };

  openedTreeNodes(data) {
    return data.map(item => {
      let a = this.state.open;
      if (item.children) {
        this.openedTreeNodes(item.children);
      }
      a.push(item.id);
      this.setState({ open: a, checkedKeys: a }, () => {
        // console.log(this.state.open)
      });
    });
  }

  checks = () => {
    console.log('我是撤销按钮');
    this.setState(
      {
        open: this.state.haveCheckedKeys,
        checkedKeys: this.state.haveCheckedKeys,
        checkButton: !this.state.checkButton,
      },
      () => {
        // this.openedTreeNodes(this.state.treeList)
      }
    );
  };

  renderTreeNodes(data) {
    return data.map(item => {
      console.log(item.status);
      function status() {
        return (
          <div>
            <span style={{ marginRight: 5 }}>{item.text}</span>
            {item.data.status !== undefined ? (
              <Tag color="volcano">{item.data.status}</Tag>
            ) : null}{' '}
          </div>
        );
      }
      if (item.children) {
        return (
          <TreeNode title={status()} key={item.id}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={status()} key={item.id} />;
    });
  }

  goBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/knowledge/knowledgeBaseSharingNew'));
  };

  onClose = () => {
    this.setState({
      close: false,
    });
    setTimeout(() => {
      const { dispatch } = this.props;
      dispatch(routerRedux.push('/knowledge/knowledgeBaseSharingNew'));
    }, 300);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 4,
        md: 3,
      },
      wrapperCol: {
        xs: 24,
        sm: 20,
        md: 21,
      },
    };
    return (
      <Drawer
        className="zdyset"
        title={
          <span  onClick={this.onClose} style={{cursor:'pointer'}}>
             <Icon type="arrow-left" style={{ marginRight: 20 }} />
            编辑知识库分享
          </span>
        }
        placement="right"
        closable={false}
        onClose={this.onClose}
        visible={this.state.close}
        width="calc(100vw - 245px)"
        destroyOnClose
      >
        <Suspense fallback={<PageLoading />}>
          <div className={styles.der}>
            <div className={styles.dabj} style={{ padding: '0px 20px' }} />
            <Form className="zdyfroma" layout="horizontal">
              <FormItem label="共享给" {...FormItemLayont}>
                <Input
                  defaultValue={this.state.value}
                  style={{ width: 250 }}
                  onChange={this.onChange}
                  placeholder="被共享者的登录账号"
                />
              </FormItem>
              <FormItem label="共享分类" {...FormItemLayont}>
                {this.state.checkButton ? (
                  <Button size="small" onClick={this.check}>
                    全选
                  </Button>
                ) : (
                  <Button size="small" onClick={this.checks}>
                    撤销
                  </Button>
                )}
                {this.state.treeList.length === 0 ? null : (
                  <Tree
                    defaultExpandAll
                    // showLine
                    checkable
                    checkedKeys={this.state.checkedKeys}
                    onCheck={this.onCheck}
                    // showIcon
                    switcherIcon={
                      <Icon
                        type="caret-down"
                        theme="filled"
                        style={{ color: '#6093ea', fontSize: 20 }}
                      />
                    }
                  >
                    {this.renderTreeNodes(this.state.treeList)}
                  </Tree>
                )}
                {/* <div>
                  <span style={{ marginRight: 10 }}>
                    <Button onClick={this.save}>保存</Button>
                  </span>
                  <Button onClick={this.goBack}>返回</Button>
                </div> */}
              </FormItem>
            </Form>
            <div className={styles.flex}>
              <div>
                {/*<img onClick={this.goBack} src={qxbuttom} style={{ marginRight: 50 }} />*/}
                <img onClick={this.save} src={qdbuttom} />
              </div>
            </div>
          </div>
        </Suspense>
      </Drawer>
    );
  }

  save = () => {
    if (this.state.value === '') {
      message['error'](`被共享者的登录账号不能为空`);
    } else {
      if (
        this.state.checkedKeys === null ||
        this.state.checkedKeys === '' ||
        this.state.checkedKeys.length === 0
      ) {
        message['error'](`共享分类不能为空`);
      } else {
        const { dispatch } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeBaseSharingNew/fetchb',
            payload: { shareToUser: this.state.value, categoriesIds: this.state.checkedKeys },
            callback: res => {
              console.log('列表数据', res);
              if (res.status === false) {
                message['error'](`${res.msg}`);
              } else {
                message['success'](`${res.msg}`);
                setTimeout(() => {
                  dispatch(routerRedux.push('/knowledge/knowledgeBaseSharingNew'));
                }, 1000);
              }
            },
          });
        });
      }
    }
  };
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(EditShoreNew));
